/**
 * Author: YuBing 羽冰
 *  time : 2021/5/24
 * description: 获取网页后端传过来的json,没什么用的东西,自己写着玩
 *  note : 客户端ajax发送请求会有跨域问题，服务端发送请求就不会
 * dependency module: https
 */

var https = require("https");

function getHttpsJson(_option, _callback) {
  if (!_option || !_callback) {
    console.log("-----------------------");
    console.log("Enter right parameter");
    console.log("-----------------------");
    return false;
  }
  if (!_option.hostname || !_option.path || !_option.method) {
    console.log("-----------------------");
    console.log("Enter right option");
    console.log("-----------------------");
    return false;
  }
  if (!/^get|GET|POST|post$/g.test(_option.method)) {
    console.log("-----------------------");
    console.log("Enter right method");
    console.log("-----------------------");
    return false;
  }

  //发送请求
  var _server = https.request(_option, function (req) { JsonHandler(req, _callback); })
  _server.end();
}
function JsonHandler(req, _callback) {
  var JsonData = "";
  req.on("data", function (chunk) { JsonData += chunk; });
  req.on("end", function () { HttpsDataHandler(JsonData, _callback) });
  req.on("error", function (err) { console.log(err); })
}
function HttpsDataHandler(data, _callback) {
  try {
    data = JSON.parse(data);
  } catch (e) {
    data = data;
  }
  _callback(data);
}

module.exports = getHttpsJson;